package com.qyhl.module_activities.act.player.list;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.qyhl.module_activities.R;
import com.qyhl.module_activities.R2;
import com.qyhl.module_activities.act.player.detail.PlayerDetailActivity;
import com.qyhl.module_activities.utils.event.PlayerMessageEvent;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.commonlib.entity.act.PlayerBean;
import com.qyhl.webtv.commonlib.entity.act.PlayerVOBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

/**
 * 选手列表
 */
public class PlayerListFragment extends BaseFragment implements PlayerListContract.PlayerListView {
    @BindView(R2.id.player_list_recyle)
    RecyclerView mPlayerListRecyle;
    @BindView(R2.id.player_list_refresh)
    SmartRefreshLayout mPlayerListRefresh;
    @BindView(R2.id.player_list_loading)
    LoadingLayout mPlayerListLoading;
    @BindView(R2.id.participant)
    TextView participant;
    @BindView(R2.id.votenum)
    TextView votenum;
    @BindView(R2.id.amountnum)
    TextView amountnum;
    @BindView(R2.id.sorttext)
    TextView sorttext;
    @BindView(R2.id.edit_search)
    EditText edit_search;
    @BindView(R2.id.search_clear)
    ImageView search_clear;
    @BindView(R2.id.sortimg)
    ImageView sortimg;
    @BindView(R2.id.top_layout)
    RelativeLayout topLayout;

    private static final String TYPE_VOTE_HIGH = "1";
    private static final String TYPE_VOTE_SHORT = "2";
    private String type = TYPE_VOTE_HIGH;
    /**
     * 控制器
     */
    private PlayerListPresenter mPresenter;
    /**
     * 页数
     */
    private int page = 1;

    private String lastPlayerId;
    /**
     * 活动数据
     */
    private int actId;
    private int sumPlayer;
    private int voteStatus;
    private int actStatus;
    private int sumVote;
    private long pageViews;
    private boolean isHideTop;
    private boolean listEnable = true;
    //展示的数据
    private List<PlayerVOBean> mDataPlayer = new ArrayList<>();
    //存储的数据，用于从查询状态恢复
    private List<PlayerVOBean> sortPlayer = new ArrayList<>();
    /**
     * 适配器
     */
    private PlayerCommonAdapter mAdapter;
    /**
     * 当前状态是否是搜索状态
     */
    private boolean isSearch = false;

    public static PlayerListFragment newInstance(int actId, Long pageViews, Integer sumPlayer, Integer sumVote, Integer voteStatus, Integer actStatus) {
        PlayerListFragment fragment = new PlayerListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("actId", actId);
        bundle.putLong("pageViews", pageViews);
        bundle.putInt("sumPlayer", sumPlayer);
        bundle.putInt("sumVote", sumVote);
        bundle.putInt("voteStatus", voteStatus);
        bundle.putInt("actStatus", actStatus);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static PlayerListFragment newInstance(int actId, Long pageViews, Integer sumPlayer, Integer sumVote, Integer voteStatus, Integer actStatus, boolean isHideTop) {
        PlayerListFragment fragment = new PlayerListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("actId", actId);
        bundle.putLong("pageViews", pageViews);
        bundle.putInt("sumPlayer", sumPlayer);
        bundle.putInt("sumVote", sumVote);
        bundle.putInt("voteStatus", voteStatus);
        bundle.putInt("actStatus", actStatus);
        bundle.putBoolean("isHideTop", isHideTop);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_fragment_player_list, container, false);
    }

    @Override
    protected void create() {
        EventBus.getDefault().register(this);
        actId = getArguments().getInt("actId");
        sumVote = getArguments().getInt("sumVote");
        sumPlayer = getArguments().getInt("sumPlayer");
        voteStatus = getArguments().getInt("voteStatus");
        actStatus = getArguments().getInt("actStatus");
        pageViews = getArguments().getLong("pageViews");
        isHideTop = getArguments().getBoolean("isHideTop", false);
        mPresenter = new PlayerListPresenter(this);
    }

    @Override
    protected void setListener() {

    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected void onFirstVisible() {
        initView();
    }

    /**
     * 初始化View
     */
    private void initView() {
        votenum.setText(String.valueOf(sumVote));
        participant.setText(String.valueOf(sumPlayer));
        amountnum.setText(String.valueOf(pageViews));
        lastPlayerId = "0";
        if (isHideTop) {
            topLayout.setVisibility(View.GONE);
            mPresenter.getPlayerListByTime(actId + "", lastPlayerId, "2");
        } else {
            topLayout.setVisibility(View.VISIBLE);
            mPresenter.getData(actId + "", page + "", type);
        }


        mPlayerListLoading.setStatus(LoadingLayout.Loading);

        mPlayerListRefresh.setEnableLoadMore(true);
        mPlayerListRefresh.setEnableRefresh(false);
        mPlayerListRefresh.setDisableContentWhenRefresh(true);
        mPlayerListRefresh.setRefreshFooter(new ClassicsFooter(getContext()));
        mPlayerListRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (isHideTop) {
                    mPresenter.getPlayerListByTime(actId + "", lastPlayerId, "2");
                } else {
                    mPresenter.getData(actId + "", page + "", type);
                }
            }
        });
        mPlayerListRecyle.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        //添加适配器
        mAdapter = new PlayerCommonAdapter(getActivity(), R.layout.act_item_act_player, mDataPlayer, actId, mPresenter, voteStatus, actStatus);
        mPlayerListRecyle.setAdapter(mAdapter);

        mPlayerListLoading.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mPlayerListLoading.setStatus(LoadingLayout.Loading);
                page = 1;
                lastPlayerId = "0";
                if (isHideTop) {
                    mPresenter.getPlayerListByTime(actId + "", lastPlayerId, "2");
                } else {
                    mPresenter.getData(actId + "", page + "", type);
                }
            }
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (listEnable) {
                    listEnable = false;
                    PlayerVOBean player = mAdapter.getDatas().get(position);
                    int playerId = player.getPlayer().getId();
                    Bundle bundle = new Bundle();
                    bundle.putInt("playerId", playerId);
                    bundle.putInt("actId", actId);
                    bundle.putInt("voteStatus", voteStatus);
                    bundle.putInt("actStatus", actStatus);
                    bundle.putInt("width", player.getApplyCoverWidth());
                    bundle.putInt("height", player.getApplyCoverHeight());
                    bundle.putString("applyImage", player.getPlayer().getApplyUrl() + "");
                    Intent intent = new Intent(getActivity(), PlayerDetailActivity.class);
                    ActivityOptionsCompat options = ActivityOptionsCompat
                            .makeSceneTransitionAnimation(getActivity(),
                                    view.findViewById(R.id.player_avatar), "applyImg");
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 888, options.toBundle());
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        edit_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
                }
            }
        });

        edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = edit_search.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    restore();
                } else {
                    search_clear.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 888 && resultCode == 555) {
            listEnable = true;
        }
    }

    @OnClick({R2.id.search, R2.id.search_clear, R2.id.sortimg, R2.id.sorttext})
    public void onclick(View v) {
        int i = v.getId();
        if (i == R.id.search) {
            String text = edit_search.getText().toString();
            if (!TextUtils.isEmpty(text)) {
                mPlayerListLoading.setStatus(LoadingLayout.Loading);
                mPresenter.searchData(actId + "", text);
                sorttext.setVisibility(View.GONE);
                sortimg.setVisibility(View.GONE);
                isSearch = true;
            }

        } else if (i == R.id.search_clear) {
            edit_search.setText("");
            restore();

        } else if (i == R.id.sortimg) {
            sort();

        } else if (i == R.id.sorttext) {
            sort();

        } else {
        }
    }

    /**
     * 恢复状态
     */
    private void restore() {
        search_clear.setVisibility(View.GONE);
        sorttext.setVisibility(View.VISIBLE);
        sortimg.setVisibility(View.VISIBLE);
        if (isSearch) {
            isSearch = false;
            mPlayerListRefresh.setEnableLoadMore(true);
            if (sortPlayer.isEmpty()) {
                onEmpty();
            } else {
                mDataPlayer.clear();
                mDataPlayer.addAll(sortPlayer);
                mAdapter.notifyDataSetChanged();
                mPlayerListLoading.setStatus(LoadingLayout.Success);
            }
        }
    }

    /**
     * 排序选择
     */
    private void sort() {
        mPlayerListLoading.setStatus(LoadingLayout.Loading);
        if (type.equals(TYPE_VOTE_HIGH)) {
            type = TYPE_VOTE_SHORT;
            sortimg.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_activeplayer_sorting_icon_min));
        } else {
            sortimg.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_activeplayer_sorting_icon_max));
            type = TYPE_VOTE_HIGH;
        }
        page = 1;
        mPresenter.getData(actId + "", page + "", type);
    }

    @Override
    protected void onVisible() {
    }

    @Override
    protected void onHide() {
    }

    @Override
    public void onError(String string) {
        mPlayerListRefresh.finishLoadMore();

        mPlayerListLoading.setErrorText(string);
        mPlayerListLoading.setReloadButtonText("点击重试");
        mPlayerListLoading.setErrorImage(R.drawable.error_content);
        mPlayerListLoading.setStatus(LoadingLayout.Error);
    }

    @Override
    public void onSuccess(List<PlayerVOBean> data) {
        mPlayerListRefresh.finishLoadMore();
        mPlayerListLoading.setStatus(LoadingLayout.Success);

        if (isHideTop) {
            if (data != null && data.size() > 0) {
                if (lastPlayerId.equals("0")) {
                    sortPlayer.clear();
                    sortPlayer.addAll(data);
                    mDataPlayer.clear();
                    mDataPlayer.addAll(data);
                } else {
                    sortPlayer.addAll(data);
                    mDataPlayer.addAll(data);
                }
                lastPlayerId = data.get(data.size() - 1).getPlayer().getId() + "";
            }
        } else {
            if (page == 1) {
                sortPlayer.clear();
                sortPlayer.addAll(data);
                mDataPlayer.clear();
                mDataPlayer.addAll(data);
            } else {
                sortPlayer.addAll(data);
                mDataPlayer.addAll(data);
            }
            page++;
        }

        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onEmpty() {
        mPlayerListLoading.setErrorText("暂无内容");
        mPlayerListLoading.setReloadButtonText("点击重试");
        mPlayerListLoading.setErrorImage(R.drawable.error_content);
        mPlayerListLoading.setStatus(LoadingLayout.Error);
    }

    @Override
    public void onVoteError(String string) {
        Toasty.normal(getActivity(), string).show();
        mAdapter.recoveryCanVote();
    }

    @Override
    public void onVoteSuccess() {
        ActionLogUtils.getInstance().onEvent(ActionConstant.ACTIVITY_VOTE);
        updateVote(mAdapter.getMPlayerId());
        mAdapter.recoveryCanVote();
        Toasty.normal(getActivity(), "投票成功").show();
        EventBus.getDefault().post(new PlayerMessageEvent("updateAct", mAdapter.getMPlayerId()));
    }

    private void updateVote(Integer mPlayerId) {
        //投票成功后更新票数
        for (int i = 0; i < mDataPlayer.size(); i++) {
            PlayerBean player = mDataPlayer.get(i).getPlayer();
            if (player.getId().equals(mPlayerId)) {
                mDataPlayer.get(i).setVoteNumber(mDataPlayer.get(i).getVoteNumber() + 1);
                mAdapter.notifyItemChanged(i);
                break;
            }
        }
        if (isSearch) {
            //投票成功后更新票数
            for (int i = 0; i < sortPlayer.size(); i++) {
                PlayerBean player = sortPlayer.get(i).getPlayer();
                if (player.getId().equals(mPlayerId)) {
                    sortPlayer.get(i).setVoteNumber(sortPlayer.get(i).getVoteNumber() + 1);
                    break;
                }
            }
        }
        sumVote++;
        votenum.setText(String.valueOf(sumVote));
    }

    /**
     * 时间订阅
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserEvent(PlayerMessageEvent event) {
        if ("updatePlayerList".equals(event.getMessage())) {
            //详情页面投了票这里刷新
            updateVote(event.getPlayerId());
        }
    }

    /**
     * 没有更多数据
     */
    @Override
    public void notData() {
        mPlayerListLoading.setStatus(LoadingLayout.Success);
        mPlayerListRefresh.finishLoadMore();
        Toasty.normal(getContext(), getString(R.string.no_data)).show();
    }

    @Override
    public void onSearchError(String string) {
        mPlayerListLoading.setEmptyText(string);
        mPlayerListLoading.setEmptyImage(R.drawable.error_content);
        mPlayerListLoading.setStatus(LoadingLayout.Empty);
        //禁用下拉加载
        mPlayerListRefresh.setEnableLoadMore(false);
    }

    @Override
    public void onSearchSuccess(List<PlayerVOBean> data) {
        mPlayerListRefresh.finishLoadMore();
        mPlayerListLoading.setStatus(LoadingLayout.Success);
        mDataPlayer.clear();
        mDataPlayer.addAll(data);
        mAdapter.notifyDataSetChanged();
        mPlayerListRefresh.setEnableLoadMore(false);
    }
}